package com.utbm.lo54.dao.neo4j;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.graphdb.index.Index;

public class Neo4jUtility {
	private static String DB_PATH = "neo4j";
	private static Node rootNode;
	private static GraphDatabaseService graphDb;
	private static Index <Node> nodeIndex;
	
	

	private static GraphDatabaseService buildGraphDatabase() {
		try {
			graphDb= new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( DB_PATH ).
					setConfig( GraphDatabaseSettings.node_keys_indexable, "STARTDATE,EMAIL,CODE,CITY,TYPE" ).
					setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ).newGraphDatabase();
			setNodeIndex(graphDb.index().forNodes( "nodes" ));
			Transaction tx = graphDb.beginTx();
			try{
				Node n = graphDb.createNode();
				n.setProperty("id", 0);
				tx.success();
				setRootNode(n);
				}
				catch ( Exception e )
				{
				    tx.failure();
				}
				finally
				{
				    tx.finish();
				}
			
			return graphDb;
		} catch (Throwable ex) {
			System.err.println("Initial GraphDatabaseFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static GraphDatabaseService getGraphDatabase() {
		if (graphDb==null) buildGraphDatabase();
		return graphDb;
	}

	public static Node createAndIndex(String key, final Object value )
	{
	    Node node = graphDb.createNode();
	    nodeIndex.add( node, key, value );
	    return node;
	}

	public static Index <Node> getNodeIndex() {
		return nodeIndex;
	}

	public static void setNodeIndex(Index <Node> nodeInd) {
		nodeIndex = nodeInd;
	}
	
	public static void shutdownDb() {
		graphDb.shutdown();
	}

	public static Node getRootNode() {
		return rootNode;
	}

	public static void setRootNode(Node rootNode) {
		Neo4jUtility.rootNode = rootNode;
	}

	public static enum RelTypes implements RelationshipType
	{
		PROPOSED,
		PLANNED,
		SUBSCRIBED,
		LOCATED
	}

}
